package com.example.dormitory_system.service.impl;



import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.dormitory_system.domain.dto.student.ChangeRoomDTO;
import com.example.dormitory_system.domain.dto.sysuser.ChangeRoomUpdateDTO;
import com.example.dormitory_system.domain.dto.sysuser.RoomUpdateDTO;
import com.example.dormitory_system.domain.enetiy.ChangeRoom;
import com.example.dormitory_system.domain.enetiy.Room;
import com.example.dormitory_system.domain.enetiy.Student;
import com.example.dormitory_system.domain.vo.student.ChangeRoomVO;
import com.example.dormitory_system.domain.vo.sysuser.RoomListVO;
import com.example.dormitory_system.enums.ResultCode;
import com.example.dormitory_system.exception.ServiceException;
import com.example.dormitory_system.mapper.BuildingMapper;
import com.example.dormitory_system.mapper.ChangeRoomMapper;
import com.example.dormitory_system.mapper.RoomMapper;
import com.example.dormitory_system.mapper.StudentMapper;
import com.example.dormitory_system.service.RoomService;
import com.example.dormitory_system.utils.ExcelUtil;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author keenan
 * @description 针对表【tb_room(寝室表)】的数据库操作Service实现
 * @createDate 2025-03-26 15:31:07
 */
@Service
public class RoomServiceImpl extends ServiceImpl<RoomMapper, Room>
        implements RoomService {
    @Autowired
    private ChangeRoomMapper changeRoomMapper;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private BuildingMapper buildingMapper;
    @Autowired
    private RoomMapper roomMapper;

    @Override
    public int updateRoom(ChangeRoomDTO changeRoomDTO) {
        List<ChangeRoom> changeRooms = changeRoomMapper.selectList(new LambdaQueryWrapper<ChangeRoom>()
                .eq(ChangeRoom::getStudentId, changeRoomDTO.getStudentId())
                .eq(ChangeRoom::getStatus, 0));
        if (CollectionUtil.isEmpty(changeRooms))
            throw new ServiceException(ResultCode.FAILED_Record_EXISTS);
        ChangeRoom changeRoom = new ChangeRoom();
        BeanUtil.copyProperties(changeRoomDTO, changeRoom);
        Student student = studentMapper.selectOne(new LambdaQueryWrapper<Student>().select(Student::getRoomName, Student::getBuildingName)
                .eq(Student::getStudentId, changeRoomDTO.getStudentId())
                .eq(Student::getStatus, 2));
        BeanUtil.copyProperties(student, changeRoom);
        changeRoom.setStatus(0);

        return changeRoomMapper.insert(changeRoom);
    }

    @Override
    public List<ChangeRoomVO> listRoom(Long studentId, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return changeRoomMapper.selectList(new LambdaQueryWrapper<ChangeRoom>()).stream().map(item ->{
            ChangeRoomVO changeRoomVO = new ChangeRoomVO();
            BeanUtil.copyProperties(item, changeRoomVO);
            return changeRoomVO;
        }).collect(Collectors.toList());
        // 获取所有相关的 ChangeRoom 记录及其楼栋和寝室名称
        //return changeRoomMapper.selectChangeRoomsWithBuildingAndRoomNames(studentId);
    }

    @Override
    public ChangeRoomVO getRoomResult(Long studentId, Long changeRoomId) {
        ChangeRoomVO changeRoomVO = changeRoomMapper.selectChangeRoomWithNewBuildingAndRoomNames(changeRoomId, studentId);
        if (changeRoomVO == null)
            throw new ServiceException(ResultCode.FAILED_ADMIN_UNTREATED);
        return changeRoomVO;
    }

    @Override
    public int sysUpdateRoom(ChangeRoomUpdateDTO changeRoomUpdateDTO) {
        return changeRoomMapper.update(new LambdaUpdateWrapper<ChangeRoom>()
                .set(ChangeRoom::getStatus, changeRoomUpdateDTO.getStatus())
                .set(ChangeRoom::getApprovalOpinion, changeRoomUpdateDTO.getApprovalOpinion())
                .set(ChangeRoom::getNewBuildingName, changeRoomUpdateDTO.getNewBuildingName())
                .set(ChangeRoom::getRoomName, changeRoomUpdateDTO.getNewBuildingName())
                .set(ChangeRoom::getNewRoomName, changeRoomUpdateDTO.getNewRoomName())
                .eq(ChangeRoom::getChangeRoomId, changeRoomUpdateDTO.getChangeRoomId())
                .eq(ChangeRoom::getStatus, 0));
    }

    public void importRooms(MultipartFile file) throws IOException {
        try {
            List<Room> rooms = ExcelUtil.readRoomsFromExcel(file.getInputStream());
            saveBatch(rooms);
        } catch (Exception e) {
            throw new RuntimeException("Failed to import rooms from Excel", e);
        }
    }

    /**
     * 更新宿舍信息
     * @param roomUpdateDTO
     * @return
     */
    @Override
    public int updateRoom(RoomUpdateDTO roomUpdateDTO) {
         if(roomUpdateDTO == null){
             throw new ServiceException(ResultCode.FAILED_PARAMS_VALIDATE);
         }
        Long roomId = roomUpdateDTO.getRoomId();
         if (roomId == null) {
             throw new ServiceException(ResultCode.FAILED_PARAMS_VALIDATE);
         }
        Room oldroom = this.getById(roomId);
        if (oldroom == null) {
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
        }
         BeanUtils.copyProperties(roomUpdateDTO, oldroom);
        boolean result = this.updateById(oldroom);
        if (result) {
            return 1;
        }
        throw new ServiceException(ResultCode.FAILED);
    }

    @Override
    public List<RoomListVO> sysListRoom(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return roomMapper.selectList(new LambdaQueryWrapper<Room>()).stream().map(item ->
        {
            RoomListVO roomListVO = new RoomListVO();
            BeanUtil.copyProperties(item, roomListVO);
            return roomListVO;
        }).collect(Collectors.toList());
    }

    @Override
    public List<ChangeRoomVO> listchangeRoom(Integer status, String applyname, String number, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return changeRoomMapper.selectChangeRoomsWithStudent(applyname,status,number);
    }
}